package com.rpc.core;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * @author jianweiwang
 * 任务线程处理器
 */
public class TaskExecutor implements Closeable {
    private static final int CORE_POOL_SIZE = 10;
    private static final int MAX_POOL_SIZE = 100;
    private static final int QUEUE_CAPACITY = 200;
    private static final int KEEP_ALIVE_TIME = 10;

    @Override
    public void close() throws IOException {
        getInstance().shutdown();
    }

    public static class Builder {
        private static final ThreadPoolTaskExecutor EXECUTOR = buildExecutor();
    }

    private static ThreadPoolTaskExecutor getInstance() {
        return Builder.EXECUTOR;
    }

    public static void execute(Runnable runnable) {
        if (null != runnable) {
            getInstance().execute(runnable);
        }
    }

    public static <T> Future<T> submit(Callable<T> task) {
        if (null != task) {
            return getInstance().submit(task);
        }
        return null;
    }

    private static ThreadPoolTaskExecutor buildExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setThreadNamePrefix("RPC-ThreadPool-");
        pool.setCorePoolSize(CORE_POOL_SIZE);
        pool.setMaxPoolSize(MAX_POOL_SIZE);
        pool.setQueueCapacity(QUEUE_CAPACITY);
        pool.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        pool.setAwaitTerminationSeconds(3);
        pool.setWaitForTasksToCompleteOnShutdown(true);
        pool.initialize();
        return pool;
    }
}
